from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.security import OAuth2PasswordBearer
from typing import Optional

app = FastAPI()

# 设置静态文件目录（如果你有更多的前端资源文件，如CSS、JS等）
# app.mount("/static", StaticFiles(directory="static"), name="static")

# 用于模拟数据库
fake_users_db = {
    "testuser": {
        "username": "testuser",
        "password": "testpassword",  # 更改密码为 testpassword
    }
}


# OAuth2 密码模式
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# 用于接收用户名和密码的 Pydantic 模型
class LoginModel(BaseModel):
    username: str
    password: str

# 登录接口
@app.post("/login")
async def login(credentials: LoginModel):
    user = fake_users_db.get(credentials.username)
    if not user or user["password"] != credentials.password:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    return {"message": "Login successful", "username": credentials.username}

# 返回 HTML 页面
@app.get("/", response_class=HTMLResponse)
async def get_login_page():
    with open("login.html", "r") as f:
        html_content = f.read()
    return HTMLResponse(content=html_content)

# 启动时运行
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，实际应用时可以限制为前端的地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
